package com.hxci.controller;

import com.hxci.service.AiAssistantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;

@RestController
@RequestMapping("/api/ai")
public class AiController {

    @Autowired
    private AiAssistantService aiService;

    @PostMapping("/chat")
    public Map<String, Object> chat(@RequestParam String prompt, HttpSession session) {
        String reply;
        try {
            String p = prompt == null ? "" : prompt.trim();
            String lower = p.toLowerCase();
            if (p.startsWith("查询") && (p.endsWith("提交的情况") || p.endsWith("的提交情况")) && p.contains("第") && p.contains("次作业")) {
                String body = p.substring(2, p.endsWith("提交的情况") ? p.length() - 5 : p.length() - 5).trim();
                int di = body.indexOf("第");
                String bname = null;
                String ord = null;
                if (di > 0) {
                    bname = body.substring(0, di).replace("班学生", "").replace("班", "").replace("班级", "").trim();
                    ord = body.substring(di).trim();
                }
                if (bname == null || bname.isEmpty() || ord == null || !ord.contains("次作业")) {
                    reply = "请按格式：查询 班级名 第N次作业 提交的情况";
                } else {
                    String digits = ord.replaceAll("[^0-9]", "");
                    int n;
                    if (!digits.isEmpty()) {
                        try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; }
                    } else {
                        String c = ord.replace("第", "").replace("次作业", "").replace("作业", "");
                        n = toNumber(c);
                    }
                    if (n <= 0) {
                        reply = "无法识别第几次作业";
                    } else {
                        String realTitle = studentService.getTitleByIndex(n);
                        if (realTitle == null || realTitle.isEmpty()) {
                            reply = "无数据";
                        } else {
                            Map<String,Object> params = new HashMap<>();
                            params.put("bname", bname);
                            params.put("title", realTitle);
                            List<Map<String,Object>> stats = studentService.getClassSubmissionStats(params);
                            if (stats == null || stats.isEmpty()) {
                                reply = "无数据";
                            } else {
                                Map<String,Object> row = stats.get(0);
                                int total = ((Number)row.getOrDefault("totalCount", 0)).intValue();
                                int submitted = ((Number)row.getOrDefault("submittedCount", 0)).intValue();
                                int notSubmitted = Math.max(0, total - submitted);
                                StringBuilder sb = new StringBuilder();
                                sb.append("班级:").append(bname)
                                  .append(" | 第").append(n).append("次作业")
                                  .append(" | 提交人数:").append(submitted)
                                  .append(" | 未提交人数:").append(notSubmitted);
                                reply = sb.toString();
                            }
                        }
                    }
                }
            } else if (p.startsWith("统计所有") && (p.contains("未提交") || p.contains("未提")) && p.contains("第") && p.contains("次作业")) {
                String q = p.replace('+', ' ').trim();
                int di = q.indexOf("第");
                String ord = null;
                if (di >= 0) {
                    int endIdx = q.indexOf("的学生");
                    ord = endIdx > di ? q.substring(di, endIdx).trim() : q.substring(di).trim();
                }
                if (ord == null || !ord.contains("次作业")) {
                    reply = "请按格式：统计所有 第N次作业 未提交人员";
                } else {
                    String digits = ord.replaceAll("[^0-9]", "");
                    int n;
                    if (!digits.isEmpty()) {
                        try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; }
                    } else {
                        String c = ord.replace("第", "").replace("次作业", "").replace("作业", "");
                        n = toNumber(c);
                    }
                    if (n <= 0) {
                        reply = "无法识别第几次作业";
                    } else {
                        String realTitle = studentService.getTitleByIndex(n);
                        if (realTitle == null || realTitle.isEmpty()) {
                            reply = "无数据";
                        } else {
                            java.util.Map<String,Object> params = new java.util.HashMap<>();
                            params.put("title", realTitle);
                            java.util.List<com.hxci.pojo.student> list = studentService.getUnsubmittedStudents(params);
                            if (list == null || list.isEmpty()) {
                                reply = "该次作业暂无未提交人员";
                            } else {
                                StringBuilder sb = new StringBuilder();
                                sb.append("第").append(n).append("次作业 | 未提交人数:").append(list.size()).append("\n");
                                for (com.hxci.pojo.student x : list) {
                                    sb.append(formatSimpleLine(x)).append("\n");
                                }
                                reply = sb.toString().trim();
                            }
                        }
                    }
                }
            } else if (p.startsWith("统计所有") && p.contains("提交人员") && p.contains("第") && p.contains("次作业")) {
                String q = p.replace('+', ' ').trim();
                int di = q.indexOf("第");
                String ord = di >= 0 ? q.substring(di).trim() : null;
                if (ord == null || !ord.contains("次作业")) {
                    reply = "请按格式：统计所有 第N次作业 提交人员";
                } else {
                    String digits = ord.replaceAll("[^0-9]", "");
                    int n;
                    if (!digits.isEmpty()) { try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; } }
                    else { String c = ord.replace("第", "").replace("次作业", "").replace("作业", ""); n = toNumber(c); }
                    if (n <= 0) {
                        reply = "无法识别第几次作业";
                    } else {
                        String realTitle = studentService.getTitleByIndex(n);
                        if (realTitle == null || realTitle.isEmpty()) {
                            reply = "无数据";
                        } else {
                            java.util.Map<String,Object> params = new java.util.HashMap<>();
                            params.put("title", realTitle);
                            java.util.List<com.hxci.pojo.student> data = studentService.getStudentDataRaw(params);
                            if (data == null || data.isEmpty()) {
                                reply = "无数据";
                            } else {
                                java.util.List<com.hxci.pojo.student> submittedList = new java.util.ArrayList<>();
                                for (com.hxci.pojo.student s : data) { if (isSubmitted(s.getScore())) { submittedList.add(s); } }
                                StringBuilder sb = new StringBuilder();
                                sb.append("第").append(n).append("次作业 | 已提交人数:").append(submittedList.size()).append("\n");
                                for (com.hxci.pojo.student x : submittedList) { sb.append(formatSimpleLine(x)).append("\n"); }
                                reply = sb.toString().trim();
                            }
                        }
                    }
                }
            } else if (p.startsWith("统计所有") && p.endsWith("的提交情况") && p.contains("第") && p.contains("次作业")) {
                String q = p.replace('+', ' ').trim();
                int di = q.indexOf("第");
                String ord = di >= 0 ? q.substring(di, q.indexOf("的提交情况") >= 0 ? q.indexOf("的提交情况") : q.length()).trim() : null;
                if (ord == null || !ord.contains("次作业")) {
                    reply = "请按格式：统计所有 第N次作业 的提交情况";
                } else {
                    String digits = ord.replaceAll("[^0-9]", "");
                    int n;
                    if (!digits.isEmpty()) { try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; } }
                    else { String c = ord.replace("第", "").replace("次作业", "").replace("作业", ""); n = toNumber(c); }
                    if (n <= 0) {
                        reply = "无法识别第几次作业";
                    } else {
                        String realTitle = studentService.getTitleByIndex(n);
                        if (realTitle == null || realTitle.isEmpty()) {
                            reply = "无数据";
                        } else {
                            java.util.Map<String,Object> params = new java.util.HashMap<>();
                            params.put("title", realTitle);
                            java.util.List<java.util.Map<String,Object>> stats = studentService.getClassSubmissionStats(params);
                            if (stats == null || stats.isEmpty()) {
                                reply = "无数据";
                            } else {
                                int total = 0, submitted = 0;
                                for (java.util.Map<String,Object> row : stats) {
                                    total += ((Number)row.getOrDefault("totalCount", 0)).intValue();
                                    submitted += ((Number)row.getOrDefault("submittedCount", 0)).intValue();
                                }
                                int notSubmitted = Math.max(0, total - submitted);
                                reply = new StringBuilder()
                                        .append("第").append(n).append("次作业")
                                        .append(" | 总人数:").append(total)
                                        .append(" | 已提交:").append(submitted)
                                        .append(" | 未提交:").append(notSubmitted)
                                        .toString();
                            }
                        }
                    }
                }
            } else if ((p.startsWith("将") || p.startsWith("更改")) && (p.contains("成绩修改为") || p.contains("成绩改为") || p.contains("成绩为"))) {
                String phrase;
                if (p.contains("成绩修改为")) {
                    phrase = "成绩修改为";
                } else if (p.contains("成绩改为")) {
                    phrase = "成绩改为";
                } else {
                    phrase = "成绩为";
                }
                String name;
                String title;
                String score;
                int startIdx = p.startsWith("将") ? 1 : 2;
                String rest = p.substring(startIdx).trim();
                if (rest.startsWith("学生")) {
                    rest = rest.substring(2).trim();
                }
                int deIdx = rest.indexOf('的');
                int phIdx = rest.indexOf(phrase);
                if (deIdx >= 0 && phIdx > deIdx) {
                    name = rest.substring(0, deIdx).trim();
                    title = rest.substring(deIdx + 1, phIdx).replace("的", "").trim();
                    if (title.startsWith("第") && title.endsWith("次作业")) {
                        String digits = title.replaceAll("[^0-9]", "");
                        int n;
                        if (!digits.isEmpty()) {
                            try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; }
                        } else {
                            String c = title.replace("第", "").replace("次作业", "").replace("作业", "");
                            n = toNumber(c);
                        }
                        if (n > 0) {
                            String realTitle = studentService.getTitleByIndex(n);
                            if (realTitle != null && !realTitle.isEmpty()) {
                                title = realTitle;
                            }
                        }
                    } else if (title.startsWith("作业")) {
                        String c = title.replace("作业", "").trim();
                        int n = toNumber(c);
                        if (n > 0) {
                            String realTitle = studentService.getTitleByIndex(n);
                            if (realTitle != null && !realTitle.isEmpty()) {
                                title = realTitle;
                            }
                        }
                    }
                    score = rest.substring(phIdx + phrase.length()).trim();
                    int affected = studentService.updateScoreByNameAndTitle(name, title, score);
                    if (affected > 0) {
                        reply = "已修改: 姓名:" + name + " | 作业:" + title + " | 成绩:" + score + " | 影响行数:" + affected;
                    } else {
                        reply = "未找到匹配记录或更新失败";
                    }
                } else {
                    reply = "格式不正确，请使用：将姓名的作业标题成绩改为分数";
                }
            } else if (p.startsWith("查询学生") && p.contains("作业") && p.contains("成绩")) {
                String body = p.substring(4).trim();
                if (body.endsWith("成绩")) {
                    body = body.substring(0, body.length() - 2).trim();
                }
                String name = null;
                String title = null;
                int di = body.indexOf("第");
                if (di > 0 && body.contains("次作业")) {
                    name = body.substring(0, di).replace("的", "").trim();
                    String ord = body.substring(di).trim();
                    String digits = ord.replaceAll("[^0-9]", "");
                    int n;
                    if (!digits.isEmpty()) {
                        try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; }
                    } else {
                        String c = ord.replace("第", "").replace("次作业", "").replace("作业", "");
                        n = toNumber(c);
                    }
                    if (n > 0) {
                        String realTitle = studentService.getTitleByIndex(n);
                        if (realTitle != null && !realTitle.isEmpty()) {
                            title = realTitle;
                        }
                    }
                } else {
                    int ti = body.indexOf("作业");
                    if (ti > 0) {
                        name = body.substring(0, ti).replace("的", "").trim();
                        title = body.substring(ti).trim();
                    }
                }
                if (name == null || name.isEmpty() || title == null || title.isEmpty()) {
                    List<com.hxci.pojo.student> list = studentService.getSubmissionsByName(body.replace("学生", "").replace("的成绩", "").trim());
                    if (list == null || list.isEmpty()) {
                        reply = "未查询到该学生提交记录";
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (com.hxci.pojo.student x : list) {
                            sb.append(getDisplayTitle(x))
                              .append(" | 分数:")
                              .append(x.getScore() == null || x.getScore().isEmpty() ? "空" : x.getScore())
                              .append(" | 班级:")
                              .append(x.getBname() == null ? "" : x.getBname())
                              .append(" | 姓名:")
                              .append(x.getName() == null ? "" : x.getName())
                              .append(" | 学号:")
                              .append(x.getSno() == null ? "" : x.getSno())
                              .append("\n");
                        }
                        reply = sb.toString().trim();
                    }
                } else {
                    List<com.hxci.pojo.student> list = studentService.getSubmissionsByNameAndTitle(name, title);
                    if (list == null || list.isEmpty()) {
                        reply = "未查询到该学生该次作业记录";
                    } else {
                        com.hxci.pojo.student x = list.get(0);
                        StringBuilder sb = new StringBuilder();
                        sb.append(getDisplayTitle(x))
                          .append(" | 分数:")
                          .append(x.getScore() == null || x.getScore().isEmpty() ? "空" : x.getScore())
                          .append(" | 班级:")
                          .append(x.getBname() == null ? "" : x.getBname())
                          .append(" | 姓名:")
                          .append(x.getName() == null ? "" : x.getName())
                          .append(" | 学号:")
                          .append(x.getSno() == null ? "" : x.getSno());
                        reply = sb.toString();
                    }
                }
            } else if (lower.startsWith("查学生") || lower.startsWith("查询学生")) {
                String name = p.replaceFirst("^查学生|^查询学生", "").trim();
                if (name.endsWith("的成绩")) {
                    name = name.substring(0, name.length() - 3).trim();
                }
                List<com.hxci.pojo.student> list = studentService.getSubmissionsByName(name);
                if (list == null || list.isEmpty()) {
                    reply = "未查询到该学生提交记录";
                } else {
                    StringBuilder sb = new StringBuilder();
                    for (com.hxci.pojo.student x : list) {
                        sb.append(getDisplayTitle(x))
                          .append(" | 分数:")
                          .append(x.getScore() == null || x.getScore().isEmpty() ? "空" : x.getScore())
                          .append(" | 班级:")
                          .append(x.getBname() == null ? "" : x.getBname())
                          .append(" | 姓名:")
                          .append(x.getName() == null ? "" : x.getName())
                          .append(" | 学号:")
                          .append(x.getSno() == null ? "" : x.getSno())
                          .append("\n");
                    }
                    reply = sb.toString().trim();
                }
            } else if (p.endsWith("的提交情况") && !p.startsWith("统计") && p.length() > 5) {
                String body = p.substring(0, p.length() - 5).trim();
                String bname = null;
                String title = null;
                int idx = body.indexOf("作业");
                if (idx > 0) {
                    bname = body.substring(0, idx).replace("班学生", "").replace("班", "").trim();
                    title = body.substring(idx).trim();
                } else {
                    String t = body.replace("班学生", " ").replace("班", " ").trim();
                    String[] parts = t.split("\\s+");
                    if (parts.length >= 2) {
                        bname = parts[0];
                        title = parts[1];
                    }
                }
                if (bname == null || title == null || bname.isEmpty() || title.isEmpty()) {
                    reply = "请按格式：班级名作业标题的提交情况";
                } else {
                    if (title.startsWith("第") && title.endsWith("次作业")) {
                        String digits = title.replaceAll("[^0-9]", "");
                        int n;
                        if (!digits.isEmpty()) {
                            try { n = Integer.parseInt(digits); } catch (Exception e) { n = 0; }
                        } else {
                            String c = title.replace("第", "").replace("次作业", "");
                            n = toNumber(c);
                        }
                        if (n > 0) {
                            String realTitle = studentService.getTitleByIndex(n);
                            if (realTitle != null && !realTitle.isEmpty()) {
                                title = realTitle;
                            }
                        }
                    }
                    Map<String,Object> params = new HashMap<>();
                    params.put("bname", bname);
                    params.put("title", title);
                    List<Map<String,Object>> stats = studentService.getClassSubmissionStats(params);
                    if (stats == null || stats.isEmpty()) {
                        reply = "无数据";
                    } else {
                        Map<String,Object> row = stats.get(0);
                        int total = ((Number)row.getOrDefault("totalCount", 0)).intValue();
                        int submitted = ((Number)row.getOrDefault("submittedCount", 0)).intValue();
                        int notSubmitted = Math.max(0, total - submitted);
                        StringBuilder sb = new StringBuilder();
                        sb.append("班级:").append(bname)
                          .append(" | 作业:").append(title)
                          .append(" | 已提交:").append(submitted)
                          .append(" | 未提交:").append(notSubmitted)
                          .append(" | 总人数:").append(total);
                        reply = sb.toString();
                    }
                }
            } else if (p.startsWith("查询") && p.endsWith("的成绩") && p.length() > 4) {
                String name = p.substring(2, p.length() - 3).trim();
                name = name.replaceFirst("^学生", "").trim();
                List<com.hxci.pojo.student> list = studentService.getSubmissionsByName(name);
                if (list == null || list.isEmpty()) {
                    reply = "未查询到该学生提交记录";
                } else {
                    StringBuilder sb = new StringBuilder();
                    for (com.hxci.pojo.student x : list) {
                        sb.append(getDisplayTitle(x))
                          .append(" | 分数:")
                          .append(x.getScore() == null || x.getScore().isEmpty() ? "空" : x.getScore())
                          .append(" | 班级:")
                          .append(x.getBname() == null ? "" : x.getBname())
                          .append(" | 姓名:")
                          .append(x.getName() == null ? "" : x.getName())
                          .append(" | 学号:")
                          .append(x.getSno() == null ? "" : x.getSno())
                          .append("\n");
                    }
                    reply = sb.toString().trim();
                }
            } else if (p.startsWith("统计") && p.endsWith("的提交情况") && p.length() > 6) {
                String body = p.substring(2, p.length() - 5).trim();
                String bname = null;
                String title = null;
                int idx = body.indexOf("作业");
                if (idx > 0) {
                    bname = body.substring(0, idx).replace("班学生", "").replace("班", "").trim();
                    title = body.substring(idx).trim();
                } else {
                    String t = body.replace("班学生", " ").replace("班", " ").trim();
                    String[] parts = t.split("\\s+");
                    if (parts.length >= 2) {
                        bname = parts[0];
                        title = parts[1];
                    }
                }
                if (bname == null || title == null || bname.isEmpty() || title.isEmpty()) {
                    reply = "请按格式：统计班级 班级名 作业标题 的提交情况";
                } else {
                    java.util.Map<String,Object> params = new java.util.HashMap<>();
                    params.put("bname", bname);
                    params.put("title", title);
                    java.util.List<com.hxci.pojo.student> data = studentService.getStudentDataRaw(params);
                    if (data == null || data.isEmpty()) {
                        reply = "无数据";
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (com.hxci.pojo.student s : data) {
                            String sc = s.getScore();
                            boolean submitted = false;
                            if (sc != null && !sc.isEmpty()) {
                                try {
                                    submitted = new java.math.BigDecimal(sc).compareTo(java.math.BigDecimal.ONE) >= 0;
                                } catch (Exception ignore) {
                                    submitted = true;
                                }
                            }
                            sb.append((s.getBname() == null ? "" : s.getBname()))
                              .append(" | ")
                              .append((s.getName() == null ? "" : s.getName()))
                              .append(" | 学号:")
                              .append((s.getSno() == null ? "" : s.getSno()))
                              .append(" | ")
                              .append(title)
                              .append(" | 分数:")
                              .append(sc == null || sc.isEmpty() ? "空" : sc)
                              .append(" | ")
                              .append(submitted ? "已提交" : "未提交")
                              .append("\n");
                        }
                        reply = sb.toString().trim();
                    }
                }
            } else if (p.startsWith("统计") && p.contains("未提交") && p.length() > 4) {
                String body = p.substring(2).trim();
                int ntIdx = body.indexOf("未提交");
                String scope = ntIdx > 0 ? body.substring(0, ntIdx).trim() : body;
                String kind = ntIdx >= 0 ? body.substring(ntIdx).trim() : "";
                String bname = null;
                String title = null;
                int ti = scope.indexOf("作业");
                if (ti > 0) {
                    bname = scope.substring(0, ti).replace("班学生", "").replace("班级", "").replace("班", "").trim();
                    title = scope.substring(ti).trim();
                } else {
                    String t = scope.replace("班学生", " ").replace("班级", " ").replace("班", " ").trim();
                    String[] parts = t.split("\\s+");
                    if (parts.length >= 2) {
                        bname = parts[0];
                        title = parts[1];
                    }
                }
                if (bname == null || title == null || bname.isEmpty() || title.isEmpty()) {
                    reply = "请按格式：统计班级 班级名 作业标题 未提交人员/人数";
                } else {
                    String nt = normalizeTitle(title);
                    java.util.Map<String,Object> params = new java.util.HashMap<>();
                    params.put("bname", bname);
                    params.put("title", nt);
                    java.util.List<com.hxci.pojo.student> list = studentService.getUnsubmittedStudents(params);
                    if (kind.contains("人数")) {
                        int n = list == null ? 0 : list.size();
                        reply = "班级:" + bname + " | 标题:" + nt + " | 未提交人数:" + n;
                    } else {
                        if (list == null || list.isEmpty()) {
                            reply = "班级:" + bname + " | 标题:" + nt + " | 未提交人员: 无";
                        } else {
                            StringBuilder sb = new StringBuilder();
                            sb.append("班级:").append(bname).append(" | 标题:").append(nt).append(" | 未提交人员:\n");
                            for (com.hxci.pojo.student x : list) {
                                sb.append((x.getBname() == null ? "" : x.getBname()))
                                  .append(" | ")
                                  .append((x.getName() == null ? "" : x.getName()))
                                  .append(" | 学号:")
                                  .append((x.getSno() == null ? "" : x.getSno()))
                                  .append("\n");
                            }
                            reply = sb.toString().trim();
                        }
                    }
                }
            } else if (lower.startsWith("查询") || lower.startsWith("查找") || lower.startsWith("列出")) {
                String q = p.substring(2).trim();
                boolean wantUnsubmitted = q.contains("未提交");
                String bname = null;
                String title = null;
                String name = null;
                int bi = q.indexOf("班级");
                if (bi >= 0) {
                    String rest = q.substring(bi + 2).trim();
                    int space = rest.indexOf(' ');
                    bname = space >= 0 ? rest.substring(0, space).trim() : rest.trim();
                }
                int ti = q.indexOf("作业");
                if (ti >= 0) {
                    String rest2 = q.substring(ti).trim();
                    int space2 = rest2.indexOf(' ');
                    title = space2 >= 0 ? rest2.substring(0, space2).trim() : rest2.trim();
                }
                int si = q.indexOf("学生");
                if (si >= 0) {
                    String rest3 = q.substring(si + 2).trim();
                    name = rest3.replace("的成绩", "").trim();
                }
                if (name != null && !name.isEmpty()) {
                    List<com.hxci.pojo.student> list = studentService.getSubmissionsByName(name);
                    if (list == null || list.isEmpty()) {
                        reply = "未查询到该学生提交记录";
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (com.hxci.pojo.student x : list) {
                            sb.append(formatFullLine(x));
                            sb.append("\n");
                        }
                        reply = sb.toString().trim();
                    }
                } else if (wantUnsubmitted && (bname != null || title != null)) {
                    java.util.Map<String,Object> params = new java.util.HashMap<>();
                    params.put("bname", bname);
                    params.put("title", title);
                    java.util.List<com.hxci.pojo.student> list = studentService.getUnsubmittedStudents(params);
                    if (list == null || list.isEmpty()) {
                        reply = "该范围内暂无未提交学生";
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (com.hxci.pojo.student x : list) {
                            sb.append(formatSimpleLine(x));
                            sb.append("\n");
                        }
                        reply = sb.toString().trim();
                    }
                } else if ((bname != null && !bname.isEmpty()) || (title != null && !title.isEmpty())) {
                    java.util.Map<String,Object> params = new java.util.HashMap<>();
                    params.put("bname", bname);
                    params.put("title", title);
                    java.util.List<com.hxci.pojo.student> data = studentService.getStudentDataRaw(params);
                    if (data == null || data.isEmpty()) {
                        reply = "无数据";
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (com.hxci.pojo.student s : data) {
                            String sc = s.getScore();
                            boolean submitted = isSubmitted(sc);
                            sb.append(formatWithTitleLine(s, title, sc, submitted));
                            sb.append("\n");
                        }
                        reply = sb.toString().trim();
                    }
                } else {
                    reply = "请提供查询范围，如：查询 班级 计科一班 作业一 或 查询 学生 张三 的成绩";
                }
            } else {
                List<Message> history = (List<Message>) session.getAttribute("ai_history");
                if (history == null) {
                    history = new ArrayList<>();
                    Message systemMessage = Message.builder().role(Role.SYSTEM.getValue()).content("你是一个友好的助理，回答简洁准确。").build();
                    history.add(systemMessage);
                }
                Message userMessage = Message.builder().role(Role.USER.getValue()).content(prompt).build();
                history.add(userMessage);
                reply = aiService.getAnswer(history);
                Message assistantMessage = Message.builder().role(Role.ASSISTANT.getValue()).content(reply).build();
                history.add(assistantMessage);
                session.setAttribute("ai_history", history);
            }
        } catch (Exception e) {
            reply = "错误:" + e.getMessage();
        }
        Map<String, Object> res = new HashMap<>();
        res.put("reply", reply);
        return res;
    }

    private int toNumber(String c) {
        if (c == null || c.isEmpty()) return 0;
        c = c.replace("（", "").replace("）", "").replace("(", "").replace(")", "").trim();
        String digits = c.replaceAll("[^0-9]", "");
        if (!digits.isEmpty()) {
            try { return Integer.parseInt(digits); } catch (Exception e) { return 0; }
        }
        int val = 0;
        int tenIdx = c.indexOf("十");
        if (tenIdx >= 0) {
            int left = tenIdx == 0 ? 1 : mapChinese(c.substring(0, tenIdx));
            int right = tenIdx == c.length() - 1 ? 0 : mapChinese(c.substring(tenIdx + 1));
            if (left <= 0) left = 1;
            val = left * 10 + right;
        } else {
            val = mapChinese(c);
        }
        return val;
    }

    private int mapChinese(String s) {
        if (s == null || s.isEmpty()) return 0;
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            int v = 0;
            switch (ch) {
                case '一': v = 1; break;
                case '二': v = 2; break;
                case '三': v = 3; break;
                case '四': v = 4; break;
                case '五': v = 5; break;
                case '六': v = 6; break;
                case '七': v = 7; break;
                case '八': v = 8; break;
                case '九': v = 9; break;
                case '零': v = 0; break;
                default: v = 0; break;
            }
            total = total * 10 + v;
        }
        return total;
    }

    @Autowired
    private com.hxci.service.StudentService studentService;

    @PostMapping("/student-submissions")
    public Map<String,Object> studentSubmissions(@RequestParam String name){
        Map<String,Object> res = new HashMap<>();
        res.put("list", studentService.getSubmissionsByName(name));
        return res;
    }

   @PostMapping("/class-stats")
   public Map<String,Object> classStats(@RequestParam(required=false) String bname,
                                        @RequestParam(required=false) String title){
        String nt = normalizeTitle(title);
        Map<String,Object> params = new HashMap<>();
        params.put("bname", bname);
        params.put("title", nt);
        Map<String,Object> res = new HashMap<>();
        res.put("list", studentService.getClassSubmissionStats(params));
        return res;
   }

   @PostMapping("/unsubmitted")
   public Map<String,Object> unsubmitted(@RequestParam(required=false) String bname,
                                         @RequestParam(required=false) String title){
        String nt = normalizeTitle(title);
        Map<String,Object> params = new HashMap<>();
        params.put("bname", bname);
        params.put("title", nt);
        Map<String,Object> res = new HashMap<>();
        res.put("list", studentService.getUnsubmittedStudents(params));
        return res;
   }

   @PostMapping("/class-submissions")
   public java.util.Map<String,Object> classSubmissions(@RequestParam String bname,
                                                        @RequestParam String title){
        String nt = normalizeTitle(title);
        java.util.Map<String,Object> params = new java.util.HashMap<>();
        params.put("bname", bname);
        params.put("title", nt);
        java.util.List<com.hxci.pojo.student> data = studentService.getStudentDataRaw(params);
        java.util.List<java.util.Map<String,Object>> list = new java.util.ArrayList<>();
        for(com.hxci.pojo.student s : data){
            String sc = s.getScore();
            boolean submitted = false;
            if(sc != null && !sc.isEmpty()){
                try {
                    submitted = new java.math.BigDecimal(sc).compareTo(java.math.BigDecimal.ONE) >= 0;
                } catch (Exception ignore) {
                    submitted = true;
                }
            }
            java.util.Map<String,Object> row = new java.util.HashMap<>();
            row.put("bname", s.getBname());
            row.put("title", nt);
            row.put("name", s.getName());
            row.put("sno", s.getSno());
            row.put("score", sc);
            row.put("submitted", submitted);
            list.add(row);
        }
        java.util.Map<String,Object> res = new java.util.HashMap<>();
        res.put("list", list);
        return res;
   }

    private boolean isSubmitted(String sc){
        if(sc == null || sc.isEmpty()) return false;
        try{
            return new java.math.BigDecimal(sc).compareTo(java.math.BigDecimal.ONE) >= 0;
        }catch(Exception e){
            return true;
        }
    }

    private String normalizeTitle(String title){
        if(title == null) return null;
        String t = title.trim();
        if(t.isEmpty()) return t;
        if(t.startsWith("第") && t.endsWith("次作业")){
            String digits = t.replaceAll("[^0-9]", "");
            int n;
            if(!digits.isEmpty()){
                try{ n = Integer.parseInt(digits); }catch(Exception e){ n = 0; }
            }else{
                String c = t.replace("第","" ).replace("次作业","" ).replace("作业","" );
                n = toNumber(c);
            }
            if(n > 0){
                String real = studentService.getTitleByIndex(n);
                if(real != null && !real.isEmpty()) return real;
            }
        } else if(t.startsWith("作业")){
            String c = t.replace("作业","" ).trim();
            int n = toNumber(c);
            if(n > 0){
                String real = studentService.getTitleByIndex(n);
                if(real != null && !real.isEmpty()) return real;
            }
        }
        return t;
    }

    private String formatSimpleLine(com.hxci.pojo.student x){
        StringBuilder sb = new StringBuilder();
        sb.append(x.getBname() == null ? "" : x.getBname())
          .append(" | ")
          .append(x.getName() == null ? "" : x.getName())
          .append(" | 学号:")
          .append(x.getSno() == null ? "" : x.getSno());
        return sb.toString();
    }

    private String formatFullLine(com.hxci.pojo.student x){
        StringBuilder sb = new StringBuilder();
        sb.append(getDisplayTitle(x))
          .append(" | 分数:")
          .append(x.getScore() == null || x.getScore().isEmpty() ? "空" : x.getScore())
          .append(" | 班级:")
          .append(x.getBname() == null ? "" : x.getBname())
          .append(" | 姓名:")
          .append(x.getName() == null ? "" : x.getName())
          .append(" | 学号:")
          .append(x.getSno() == null ? "" : x.getSno());
        return sb.toString();
    }

    private String formatWithTitleLine(com.hxci.pojo.student s, String title, String sc, boolean submitted){
        StringBuilder sb = new StringBuilder();
        sb.append(s.getBname() == null ? "" : s.getBname())
          .append(" | ")
          .append(s.getName() == null ? "" : s.getName())
          .append(" | 学号:")
          .append(s.getSno() == null ? "" : s.getSno())
          .append(" | ")
          .append(title == null ? "" : title)
          .append(" | 分数:")
          .append(sc == null || sc.isEmpty() ? "空" : sc)
          .append(" | ")
          .append(submitted ? "已提交" : "未提交");
        return sb.toString();
    }

    private String getDisplayTitle(com.hxci.pojo.student x){
        String t = x.getTitle();
        if(t != null && !t.isEmpty()) return t;
        Integer w = x.getWid();
        if(w != null && w > 0) return "第" + w + "次作业";
        return "无标题";
    }
}